package org.roger.collector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.Scorer;

/**
 * 自定义收集器
 * 每个匹配的文档都会调用collect方法，对匹配的文档做进一步的处理
 * @author luoweiyi
 */
public class FilePathCollector extends Collector{
	
	private Scorer scorer;
	
	//所有文档的path集合
	private String[] allPaths;
	//所有文档分数的集合
	private Float[] allScorers;
	
	//匹配文档的path几集合
	private List<String> paths = new ArrayList<String>();
	//匹配文档分数
	private List<Float> scorers = new ArrayList<Float>();

	@Override
	public void setScorer(Scorer scorer) throws IOException {
		if(this.scorer == null)
			this.scorer = scorer;
	}

	@Override
	public void collect(int doc) throws IOException {
		paths.add(allPaths[doc]);
		scorers.add(allScorers[doc]);
	}

	@Override
	public void setNextReader(AtomicReaderContext context) throws IOException {
		int numDoc = context.reader().numDocs();
		allPaths = new String[numDoc];
		allScorers = new Float[numDoc];
		BinaryDocValues bits = FieldCache.DEFAULT.getTerms(context.reader(), "path", true);
		for(int i = 0; i < numDoc; i++){
			allPaths[i] = bits.get(i).utf8ToString();
			scorer.nextDoc();
			allScorers[i] = scorer.score();
		}
	}
	
	public List<String> getPaths(){
		return paths;
	}
	
	public List<Float> getScorers(){
		return scorers;
	}

	@Override
	public boolean acceptsDocsOutOfOrder() {
		return true;
	}
}
